#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import requests


class OutPutUse(object):
    def __init__(self):
        self.real_download = True
        self.save_root_dir = 'output'
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
        }

    def download_and_save(self, url, mj_name):
        print('正在下载图片:', mj_name, url)
        if self.real_download is False:
            return
        save_dir = self.save_root_dir + os.path.sep + mj_name
        if os.path.exists(save_dir) is False:
            os.makedirs(save_dir)
        save_file = save_dir + os.path.sep + url.split("/")[-1]

        if os.path.exists(save_file):
            print('本地已经存在该图片:', mj_name, url)
            return
        try:
            html = requests.get(url, timeout=60, headers=self.headers)
            # html.raise_for_status()
            # html.encoding = html.apparent_encoding
            with open(save_file, 'wb') as file:
                file.write(html.content)
                file.flush()
                file.close()
        except Exception:
            print('#download_and_save# 下载{0}的图片:{1}出错！'.format(mj_name, url))


if __name__ == '__main__':
    url = 'https://mtl.ttsqgs.com/images/img/7298/1.jpg'
    OutPutUse().download_and_save(url, 'demo')
